<template>
	<div class="m5" style="overflow-y: scroll; height: 80vh;">
		<div @click="init" style="user-select: none;">员工列表</div>
		<el-tree empty-text="没有数据" :data="data" :props="defaultProps" @node-click="onClickNode" />
	</div>
</template>

<script setup lang="ts">
import { service, type EmplInfo2 } from '@/service/api';
import { run } from '@/utils/ui';
import { ref } from 'vue';
import { selectEmpl, selectOrg } from '@/service/global';

interface Tree {
	label: string,
	children: Tree[],
	isOrg: boolean,
	data?: any,
}

const defaultProps = {
	children: 'children',
	label: 'label',
}

const data = ref<Tree[]>([]);

function newTree(orgs: string[]) {
	return orgs.map<Tree>((org) => {
		return {
			label: org,
			children: [],
			isOrg: true,
		};
	});
}

function newTreeWithEmpl(empls: EmplInfo2[]) {
	return empls.map<Tree>((empl) => {
		return {
			label: empl.name,
			children: [],
			isOrg: false,
			data: empl
		};
	});
}

async function init() {

	run(async () => {
		const orgs = await service.selectOrgs();
		data.value = newTree(orgs);
	})
}

async function onClickNode(data: Tree) {
	if (!data.isOrg) {
		selectEmpl.value = data.data as EmplInfo2;
		return;
	}
	selectOrg.value = data.label;
	run(async () => {
		const empls = await service.selectEmpls(data.label);
		data.children = newTreeWithEmpl(empls);
	})
}

init();

</script>
